package com.china08.yxyapi.api.home.resource;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.http.MediaType;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.china08.yxyapi.api.YxyApiBaseController;
import com.china08.yxyapi.entity.db.res.YxyResBookContents;
import com.china08.yxyapi.entity.db.res.YxyResResource;
import com.china08.yxyapi.entity.es.ElasticYxyResResource;
import com.china08.yxyapi.entity.mg.user.YxyUserMark;
import com.china08.yxyapi.model.YxyApiPageReqModel;
import com.china08.yxyapi.model.YxyApiRespModel;
import com.china08.yxyapi.repository.db.YxyResBookContentsRepository;
import com.china08.yxyapi.repository.db.YxyResResourceRepository;
import com.china08.yxyapi.service.yxyresource.YxyResourceService;
import com.china08.yxyapi.util.DateToolUtils;
import com.china08.yxyapi.util.EsResourceUpdateUtil;
import com.china08.yxyapi.util.FloatUtil;
import com.china08.yxyapi.util.YxyResUtil;

import io.swagger.annotations.ApiOperation;

@CrossOrigin
@RestController
public class ResourceDetailController extends YxyApiBaseController {

    @Autowired
    private YxyResUtil YxyResUtil;

    @Autowired
    private YxyResourceService yrs;

    @Autowired
    private YxyResResourceRepository yrrr;

    @Autowired
    private MongoTemplate mt;

    @Autowired
    private YxyResBookContentsRepository yrbcr;

    @ApiOperation(value = "资源详情")
    @ResponseBody
    @RequestMapping(value = "/api_yw/home/res/detail", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public RespModel find(HttpServletRequest request, HttpServletResponse response,
            @RequestBody(required = true) ReqModel reqModel) throws IllegalAccessException, InvocationTargetException {
        if (reqModel == null) {
            reqModel = new ReqModel();
        }
        RespModel model = new RespModel();
        try {
            ElasticYxyResResource elasticYxyResResource = yrs.findById(reqModel.id);
            Assert.notNull(elasticYxyResResource, "找不到资源，请刷新页面");
            Assert.isTrue(elasticYxyResResource.getStatus() == 1, "资源未审核或审核未通过");
            YxyResResource resource = yrrr.findById(reqModel.id);
            Assert.notNull(resource, "找不到资源，请刷新页面");
            resource.setPv(resource.getPv() + 1);
            yrrr.save(resource);

            // 用户属性
            String userId = getProfile(request, response).getId();

            if (StringUtils.isNotBlank(userId)) {
                String schoolId = getProfile(request, response).getSchoolId();
                if (StringUtils.isNotBlank(schoolId)) {
                    // 我的评分
                    YxyUserMark mark = mt.findOne(
                            new Query().addCriteria(Criteria.where("resId").is(reqModel.id).and("userId").is(userId)),
                            YxyUserMark.class);
                    Integer myMark = (mark == null ? 0 : mark.getMark());
                    model.myMark = myMark;
                } else {
                    model.myMark = 0;
                }
            }

            model.setExtension(elasticYxyResResource.getExtension());
            model.setId(elasticYxyResResource.getId());
            model.setUploaderName(elasticYxyResResource.getUploaderName());
            model.setUploaderSchoolName(elasticYxyResResource.getUploaderSchoolName());
            model.setIntro(elasticYxyResResource.getIntro());
            model.setTitle(elasticYxyResResource.getTitle());
            model.setFileSize(elasticYxyResResource.getFileSize());
            model.setDownloadCount(elasticYxyResResource.getDownloadCount());
            model.setPv(elasticYxyResResource.getPv());
            model.setType(elasticYxyResResource.getTypeId());
            model.setFavoriteCount(elasticYxyResResource.getFavoriteCount());
            model.setConvertStatus(elasticYxyResResource.getConvertStatus());
            model.setLocation(elasticYxyResResource.getLocation());
            model.setMark(FloatUtil.dot1(elasticYxyResResource.getMark()));
            model.setTypeName(elasticYxyResResource.getTypeName());
            model.setFormatId(elasticYxyResResource.getFormatId());
            model.setFormatName(elasticYxyResResource.getFormatName());
            model.setDuration(elasticYxyResResource.getDuration());
            if (elasticYxyResResource.getUploadTime() != null) {
                model.uploadTimeFormat = DateToolUtils.format(elasticYxyResResource.getUploadTime(),
                        DateToolUtils.FORMAT_SHORT_YMD);
            }
            List<String> bookContentId = elasticYxyResResource.getBookContentIdList();
            List<String> parentBooKcontentIds = new ArrayList<String>();
            List<String> parentBooKcontentNames = new ArrayList<String>();
            for (String string : bookContentId) {
                YxyResBookContents parentBookContents = getParent0(string);
                if (parentBookContents != null) {
                    parentBooKcontentIds.add(parentBookContents.getId());
                    parentBooKcontentNames.add(parentBookContents.getName());
                }
            }
            // model.setParentTocId(parentBooKcontentIds));
            model.setParentTocId(parentBooKcontentIds.size() > 0 ? parentBooKcontentIds.get(0) : "");
            model.setParentTocName(parentBooKcontentNames);
            model.setBookContentNames(elasticYxyResResource.getBookContentNameList());
            // 资源下载
            String download = YxyResUtil.getDownloadUrl(reqModel.id);
            model.setDownloadLocation(download);
            System.out.println("==============" + YxyResUtil.getPreviewUrl(reqModel.id));
            EsResourceUpdateUtil.updateEsResoure(reqModel.id);
            model.setPreview(YxyResUtil.getPreviewUrl(reqModel.id));
            model.setIsVip(elasticYxyResResource.getIsVip());
            model.setIsHighQualityYx(elasticYxyResResource.getIsHighQualityYx());
            model.setResVip(Boolean.valueOf(getProfile(request, response).getResVip()));
            model.setRoleId(getProfile(request, response).getRoleId());
            model.setMessage("成功");
            // EsResourcePvUpdateUtil.updateEsResoure(reqModel.id + "_1");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return model;
    }

    private YxyResBookContents getParent0(String bookContentId) {
        YxyResBookContents bookContents = yrbcr.findById(bookContentId);
        if (bookContents != null && !StringUtils.equals(bookContents.getpId(), "0")) {
            getParent0(bookContents.getpId());
        }
        return bookContents;
    }

    protected static class ReqModel extends YxyApiPageReqModel {
        public String id;

        @Override
        public void autoCheck() {
            Assert.notNull(StringUtils.defaultIfBlank(id, null), "请指定资源");
        }

    }

    public static class RespModel extends YxyApiRespModel {

        public String id;

        // 上传人名
        public String uploaderName;

        // 上传者学校明天
        public String uploaderSchoolName;

        // 资源简介
        public String intro;

        // 标题
        public String title;

        // 文件大小
        public Integer fileSize = 0;

        // 下载量
        public Long downloadCount = 0l;

        /**
         * 展示次数
         */
        public Long pv = 0l;

        /**
         * 收藏次数
         */
        public Long favoriteCount = 0l;

        // 文件的状态信息 0初始上传， 1 转码中 ，2 转码成功 ，3 转码失败
        public Integer convertStatus = 0;

        /**
         * 文件路径
         */
        public String location;

        // 评分
        public float mark = 0f;

        public String typeName;

        public String formatId;

        public String formatName;

        /** 视频文件时长 */
        public Integer duration;

        // // 父目录ID
        // public List<String> parentTocId;
        public String parentTocId;

        // 父目录名称
        public List<String> parentTocName;

        // 上传时间
        public String uploadTimeFormat = "";

        // 所属目录名称
        public List<String> bookContentNames;

        public String downloadLocation = "";

        public Integer myMark = 0;// 我的上次评分

        // 文件扩展名
        public String extension;

        public String type;

        public Boolean isVip = false;

        public Integer isHighQualityYx = 0;

        public Boolean resVip = false;

        public String roleId;

        public String getRoleId() {
            return roleId;
        }

        public void setRoleId(String roleId) {
            this.roleId = roleId;
        }

        public Boolean getResVip() {
            return resVip;
        }

        public void setResVip(Boolean resVip) {
            this.resVip = resVip;
        }

        public Boolean getIsVip() {
            return isVip;
        }

        public void setIsVip(Boolean isVip) {
            this.isVip = isVip;
        }

        public Integer getIsHighQualityYx() {
            return isHighQualityYx;
        }

        public void setIsHighQualityYx(Integer isHighQualityYx) {
            this.isHighQualityYx = isHighQualityYx;
        }

        public String getType() {
            return type;
        }

        public void setType(String type) {
            this.type = type;
        }

        public String getExtension() {
            return extension;
        }

        public void setExtension(String extension) {
            this.extension = extension;
        }

        public Integer getMyMark() {
            return myMark;
        }

        public void setMyMark(Integer myMark) {
            this.myMark = myMark;
        }

        // 预览
        public String preview = "";

        public String getId() {
            return id;
        }

        public void setId(String id) {
            this.id = id;
        }

        public String getUploaderName() {
            return uploaderName;
        }

        public void setUploaderName(String uploaderName) {
            this.uploaderName = uploaderName;
        }

        public String getUploaderSchoolName() {
            return uploaderSchoolName;
        }

        public void setUploaderSchoolName(String uploaderSchoolName) {
            this.uploaderSchoolName = uploaderSchoolName;
        }

        public String getIntro() {
            return intro;
        }

        public void setIntro(String intro) {
            this.intro = intro;
        }

        public String getTitle() {
            return title;
        }

        public void setTitle(String title) {
            this.title = title;
        }

        public Integer getFileSize() {
            return fileSize;
        }

        public void setFileSize(Integer fileSize) {
            this.fileSize = fileSize;
        }

        public Long getDownloadCount() {
            return downloadCount;
        }

        public void setDownloadCount(Long downloadCount) {
            this.downloadCount = downloadCount;
        }

        public Long getPv() {
            return pv;
        }

        public void setPv(Long pv) {
            this.pv = pv;
        }

        public Long getFavoriteCount() {
            return favoriteCount;
        }

        public void setFavoriteCount(Long favoriteCount) {
            this.favoriteCount = favoriteCount;
        }

        public Integer getConvertStatus() {
            return convertStatus;
        }

        public void setConvertStatus(Integer convertStatus) {
            this.convertStatus = convertStatus;
        }

        public String getLocation() {
            return location;
        }

        public void setLocation(String location) {
            this.location = location;
        }

        public float getMark() {
            return mark;
        }

        public void setMark(float mark) {
            this.mark = mark;
        }

        public String getTypeName() {
            return typeName;
        }

        public void setTypeName(String typeName) {
            this.typeName = typeName;
        }

        public String getFormatId() {
            return formatId;
        }

        public void setFormatId(String formatId) {
            this.formatId = formatId;
        }

        public String getFormatName() {
            return formatName;
        }

        public void setFormatName(String formatName) {
            this.formatName = formatName;
        }

        public Integer getDuration() {
            return duration;
        }

        public void setDuration(Integer duration) {
            this.duration = duration;
        }

        //
        // public List<String> getParentTocId() {
        // return parentTocId;
        // }
        //
        // public void setParentTocId(List<String> parentTocId) {
        // this.parentTocId = parentTocId;
        // }
        public String getParentTocId() {
            return parentTocId;
        }

        public void setParentTocId(String parentTocId) {
            this.parentTocId = parentTocId;
        }

        public List<String> getParentTocName() {
            return parentTocName;
        }

        public void setParentTocName(List<String> parentTocName) {
            this.parentTocName = parentTocName;
        }

        public String getUploadTimeFormat() {
            return uploadTimeFormat;
        }

        public void setUploadTimeFormat(String uploadTimeFormat) {
            this.uploadTimeFormat = uploadTimeFormat;
        }

        public List<String> getBookContentNames() {
            return bookContentNames;
        }

        public void setBookContentNames(List<String> bookContentNames) {
            this.bookContentNames = bookContentNames;
        }

        public String getDownloadLocation() {
            return downloadLocation;
        }

        public void setDownloadLocation(String downloadLocation) {
            this.downloadLocation = downloadLocation;
        }

        public String getPreview() {
            return preview;
        }

        public void setPreview(String preview) {
            this.preview = preview;
        }

    }
}
